import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { NO_REDIRECT_WHITE_LIST } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { getUserInfoApi } from '@/api/login'
import type { UserInfoType } from '@/api/login/types'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  const permissionStore = usePermissionStoreWithOut()
  const appStore = useAppStoreWithOut()
  const userStore = useUserStoreWithOut()
  if (userStore.getUserInfo) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (permissionStore.getIsAddRouters && userStore.getRoleRouters && userStore.getRoleRouters.length > 0) {
        next()
        return
      }

      // 刷新页面时重新获取用户信息，根据 privs 过滤菜单
      // roleRouters 不持久化，所以刷新后需要重新获取
      if (!userStore.getRoleRouters || userStore.getRoleRouters.length === 0) {
        try {
          const userInfoRes = await getUserInfoApi()
          const userInfo = userInfoRes.data
          
          if (userInfo && (userInfo as UserInfoType).privs) {
            const userInfoData = userInfo as UserInfoType
            // 从 privs 中提取 url 列表，用于过滤路由
            const allowedUrls = userInfoData.privs.map(priv => priv.url)
            console.log('刷新页面 - 用户权限 URL:', allowedUrls)
            // 设置角色路由
            userStore.setRoleRouters(allowedUrls)
            // 使用前端静态路由，根据 privs 过滤
            await permissionStore.generateRoutes('frontEnd', allowedUrls)
            console.log('刷新页面 - 生成的路由数量:', permissionStore.getAddRouters.length)
          } else {
            // 如果没有权限信息，使用静态路由
            await permissionStore.generateRoutes('static')
          }
        } catch (error) {
          // 如果获取用户信息失败，使用静态路由
          await permissionStore.generateRoutes('static')
        }
      } else {
        // 已有角色路由，直接使用
        const roleRouters = userStore.getRoleRouters || []

        // 是否使用动态路由
        if (appStore.getDynamicRouter) {
          appStore.serverDynamicRouter
            ? await permissionStore.generateRoutes('server', roleRouters as AppCustomRouteRecordRaw[])
            : await permissionStore.generateRoutes('frontEnd', roleRouters as string[])
        } else {
          // 不使用动态路由，根据 roleRouters（url 列表）过滤
          if (roleRouters.length > 0 && typeof roleRouters[0] === 'string') {
            // roleRouters 是 url 列表，使用前端过滤
            await permissionStore.generateRoutes('frontEnd', roleRouters as string[])
          } else {
            // 否则使用静态路由
            await permissionStore.generateRoutes('static')
          }
        }
      }

      permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
      })
      const redirectPath = from.query.redirect || to.path
      const redirect = decodeURIComponent(redirectPath as string)
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
      permissionStore.setIsAddRouters(true)
      
      // 确保路由已正确加载
      next(nextData)
    }
  } else {
    if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
